/**
 *  @file  TcpStream.h version 1.0 2007-11-20
 *  @brief Define wrapper class TemplateTcpStream for TCP socket stream.
 *  Copyright (c) 2007 by @author Zhao Jun <abitfree@gmail.com>
 */

#ifndef __TCP_STREAM_H__
#define __TCP_STREAM_H__

#include "AsynSocketHandle.h"

namespace vs {
namespace net {

/**
@brief Wrapper class for socket stream.
This class can receive/send data via the underlying socket stream, can work with TcpAcceptor and TcpConnector.
*/
template<typename SOCK>
class TemplateTcpStream : public SOCK
{
public:
	/// Default Constructor.
	TemplateTcpStream() : SOCK() {};
	
	/// Construct from an existing SocketHandle object, will take over underlying socket, and sock will be invalid.
	TemplateTcpStream(SOCK &sock);
	
	/// Send data to peer host.
	int Send(const char *msg, int len, int flags = 0);
	
	/// Receive data from peer host.
	int Recv(char *buf, int len, int flags = 0);
};


/// The blocking TCP stream class.
typedef TemplateTcpStream<SocketHandle> TcpStream;

/// The non-blocking TCP stream class.
typedef TemplateTcpStream<AsynSocketHandle> AsynTcpStream;

template<typename SOCK>
INLINE
TemplateTcpStream<SOCK>::TemplateTcpStream(SOCK &sock)
	: SOCK(sock)
{
	sock.Detach();
}

template<typename SOCK>
INLINE
int TemplateTcpStream<SOCK>::Send(const char *msg, int len, int flags)
{
	return send(GetHandle(), msg, len, flags);
}

template<typename SOCK>
INLINE
int TemplateTcpStream<SOCK>::Recv(char *buf, int len, int flags)
{
	return recv(GetHandle(), buf, len, flags);
}

}	// namespace net
}	// namespace vs

#endif	// __TCP_STREAM_H__
